#include <math.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>



double func (double x)
{
    return x * x * x * cos(x);
}


bool check_Runge(double I2, double I, double epsilon)
{
    return (fabs(I2 - I) / 3.) < epsilon;
}

void write_double_to_file(const char *filename, double data)
{
    FILE *fp = fopen(filename, "w");
    if (fp == NULL)
    {
        printf("Failed to open the file\n");
    }
    fprintf(fp, "%lg\n", data);
    fclose(fp);
}


double integrate_trap(double start, double finish, double epsilon)
{
  int num_iterations = 1;
  double last_res = 0;
  double res = -1;
  double h = 0;
  while(!check_Runge(res, last_res, epsilon))
  {
    num_iterations *= 2;
    //printf("last_res = %lg, res = %lg, doing %d iters\n", last_res, res, num_iterations);
    last_res = res;
    res = 0;
    h = (finish - start) / num_iterations;
    for(int i = 0; i < num_iterations; i++)
    {
      res += func(start + i * h + h / 2.0);
    }
    res += (func(start) + func(finish)) / 2.0;
    res *= h;
  }
  return res;
}

double *read_from_file()
{

    double *input = (double *)malloc(3 * sizeof(double));
    FILE *fp = fopen("input.txt", "r");

    if (fp == NULL)
    {
        printf("Failed to open the file\n");

    }

    for (int i = 0; i < 3; i++)
        fscanf(fp, "%lg", &input[i]);
    fclose(fp);


    return input;
}
